package com.kangyi.user.service.Impl;

import com.kangyi.entity.GuestsStaying;
import com.kangyi.user.mapper.GuestsStayingMapper;
import com.kangyi.user.mapper.HealthReportMapper;
import com.kangyi.user.service.HealthReportService;
import com.kangyi.utils.AuthUtil;
import com.kangyi.vo.DynamicHealthStatisticsVO;
import com.kangyi.vo.HealthReportVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;

/**
 * @author Blank
 * @version 1.0
 */
@Service
@Slf4j
public class HealthReportServiceImpl implements HealthReportService {

    @Autowired
    private HealthReportMapper healthReportMapper;

    @Autowired
    private GuestsStayingMapper guestsStayingMapper;


    @Override
    public DynamicHealthStatisticsVO getDynamicHealthStatistics(LocalDate begin, LocalDate end, Integer guestId, List<String> fields) {
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        Map<String, List<Object>> indicatorDataMap = new HashMap<>();
        for (String field : fields) {
            indicatorDataMap.put(field, new ArrayList<>());
        }

        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            Map<String, Object> map = new HashMap<>();
            map.put("begin", beginTime);
            map.put("end", endTime);
            map.put("guestId", guestId);

            for (String field : fields) {
                map.put("fieldName", field);
                Object result = healthReportMapper.getDynamicFieldByMap(map);
                result = result == null ? 0 : result;
                indicatorDataMap.get(field).add(result);
            }
        }

        Map<String, String> healthIndicators = new HashMap<>();
        for (Map.Entry<String, List<Object>> entry : indicatorDataMap.entrySet()) {
            String field = entry.getKey();
            List<Object> dataList = entry.getValue();
            String dataString = StringUtils.join(dataList, ",");
            healthIndicators.put(field, dataString);
        }

        String name = guestsStayingMapper.selectById(guestId).getName();

        return DynamicHealthStatisticsVO.builder()
                .name(name)
                .dateList(StringUtils.join(dateList, ","))
                .healthIndicators(healthIndicators)
                .build();
    }

    @Override
    public void getexport(HttpServletResponse response, Integer guestId) {
        // 验证用户权限和查询数据逻辑（保持不变）
        GuestsStaying guestsStaying = guestsStayingMapper.selectById(guestId);
        AuthUtil.validateUserPermission(guestsStaying.getUserId());

        LocalDate dateBegin = LocalDate.now().minusDays(30);
        LocalDate dateEnd = LocalDate.now().minusDays(1);
        LocalDateTime begin = LocalDateTime.of(dateBegin, LocalTime.MIN);
        LocalDateTime end = LocalDateTime.of(dateEnd, LocalTime.MAX);

        try (XSSFWorkbook excel = new XSSFWorkbook(Objects.requireNonNull(
                this.getClass().getClassLoader().getResourceAsStream("template/健康数据表模板.xlsx")));
             ServletOutputStream outputStream = response.getOutputStream()) {

            XSSFSheet sheet1 = excel.getSheet("Sheet1");

            // 1. 填充姓名到 2C（第2行，C列）
            Row nameRow = sheet1.getRow(1); // 第2行（索引1）
            if (nameRow == null) nameRow = sheet1.createRow(1);
            nameRow.createCell(2).setCellValue("姓名：" + guestsStayingMapper.findNameByGuestId(guestId));

            // 2. 填充时间段到 2F（第2行，F列）
            nameRow.createCell(5).setCellValue("时间段：" + dateBegin + " 至 " + dateEnd);

            // 3. 填充数据（从第6行开始，索引5）
            int rowIndex = 5;
            List<HealthReportVO> reports = healthReportMapper.findHealthReportsByGuestIdAndTimeRange(guestId, begin, end);
            if (reports != null && !reports.isEmpty()) {
                Collections.sort(reports, Comparator.comparing(HealthReportVO::getCreateTime).reversed());

                // 创建日期格式样式
                CellStyle dateCellStyle = excel.createCellStyle();
                dateCellStyle.setDataFormat(
                        excel.getCreationHelper().createDataFormat().getFormat("yyyy-MM-dd")
                );

                for (HealthReportVO report : reports) {
                    XSSFRow row = sheet1.createRow(rowIndex++);

                    // 日期 → B列（索引1）
                    Cell dateCell = row.createCell(1);
                    dateCell.setCellValue(report.getCreateTime().toLocalDate());
                    dateCell.setCellStyle(dateCellStyle);

                    // 血压 → C列（索引2）
                    String bloodPressure = "";
                    if (report.getBloodPressureSystolic() != null || report.getBloodPressureDiastolic() != null) {
                        bloodPressure =
                                (report.getBloodPressureSystolic() != null ? report.getBloodPressureSystolic() : "") + "/" +
                                        (report.getBloodPressureDiastolic() != null ? report.getBloodPressureDiastolic() : "");
                    }
                    row.createCell(2).setCellValue(bloodPressure);

                    // 血糖 → D列（索引3）
                    if (report.getBloodSugar() != null) {
                        row.createCell(3).setCellValue(report.getBloodSugar());
                    } else {
                        row.createCell(3).setCellValue("");
                    }

                    // 血脂 → E列（索引4）
                    if (report.getBloodLipids() != null) {
                        row.createCell(4).setCellValue(report.getBloodLipids());
                    } else {
                        row.createCell(4).setCellValue("");
                    }

                    // 尿酸 → F列（索引5）
                    if (report.getUricAcid() != null) {
                        row.createCell(5).setCellValue(report.getUricAcid());
                    } else {
                        row.createCell(5).setCellValue("");
                    }
                }
            }

            // 4. 写入并输出 Excel
            excel.write(outputStream);
        } catch (IOException e) {
            log.error("导出 Excel 报表失败", e);
            try {
                response.reset();
                response.setStatus(500);
                response.getWriter().write("导出 Excel 报表失败，请联系管理员");
            } catch (IOException ex) {
                log.error("向客户端返回错误信息失败", ex);
            }
        }
    }

    private String getStatusText(Integer status) {
        switch (status) {
            case 1:
                return "正常";
            case 2:
                return "偏高";
            case 3:
                return "高";
            case 4:
                return "极高";
            default:
                return "未知";
        }
    }
}
